package tree;

/**
 * @author wcj
 * @Date 2021/7/7 0:06
 * @Version 1.0
 */
public class MergeTree {

    /**
     * 合并二叉树
     * 递归：
     * ①递归方法的设计：mergeTree(TreeNode r1,TreeNode r2)其中r1,r2代表当前访问到的节点
     * ②递归出口：r1 == null && r2 == null ,返回
     * ③递归体：前序遍历
     *
     * @param r1
     * @param r2
     * @return
     */
    public static TreeNode mergeTree(TreeNode r1, TreeNode r2) {
        if (r1 == null && r2 == null) {
            return null;
        }
        if (r1 == null) {
            return r2;
        }
        if (r2 == null) {
            return r1;
        }
        TreeNode currentNode = new TreeNode(r1.val + r2.val);
        currentNode.left = mergeTree(r1.left, r2.left);
        currentNode.right = mergeTree(r1.right, r2.right);
        return currentNode;
    }
}
